package com.woniuxy.gateway.handlder;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.cloud.demo.Result;
import com.woniuxy.gateway.common.JWTHelper;
import com.woniuxy.gateway.entity.AuthUserDetails;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.WebFilterChainServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import javax.annotation.Resource;


@Component
public class AuthenticationSuccessHandler extends WebFilterChainServerAuthenticationSuccessHandler {

    @Resource
    private StringRedisTemplate srt;

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        //设置headers
        HttpHeaders headers = response.getHeaders();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        headers.add("Cache-Control", "no-store,no-cache,must-revalidate,max-age-8");
        //设置body
        byte[] dataBytes = {};
        ObjectMapper mapper = new ObjectMapper();

        AuthUserDetails utd = (AuthUserDetails) authentication.getPrincipal();
        //添加redis

        srt.opsForHash().put("shared:battery:user:login", utd.getUserId()+"", utd.getToken());
        utd.setUserPassword(null);
        //构建Result
        Result result = Result.newInstance()
                .setCode(200).setMsg("登录成功").setData(utd);

        try {
            dataBytes = mapper.writeValueAsBytes(result);
        } catch (JsonProcessingException jsonProcessingException) {
            jsonProcessingException.printStackTrace();
        }
        DataBuffer bodyDateBuffer = response.bufferFactory().wrap(dataBytes);
        return response.writeWith(Mono.just(bodyDateBuffer));
    }

}
